﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Threading;


namespace WallPaperU
{
    public partial class coverPic : Form
    {
        string title;
        string sid;
        string vips;
        string path;
        string ssinfo;
        private DataGridViewRow R1;
        public coverPic()
        {
            InitializeComponent();
        }

        private void coverPic_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
            comboBox1.Items.Clear();
            string url = "http://meik171.duapp.com/WallPaper?action=getSorts";
            string result = GetWebClient(url).Replace(" ", "").Replace("#*", "/");
            if (result != "" && result != "ER")
            {
                string[] list = result.Split('/');
                for (int i = 0; i < list.Length; i++)
                {
                    ListItem item = new ListItem();
                    string lld = list[i].Replace("#", "").Replace("*", "");
                    item.Text = lld.Split(',')[1];
                    item.Value = lld.Split(',')[0];
                    comboBox1.Items.Add(item);
                }
            }
            if (comboBox1.Items.Count >= 1) {
                comboBox1.SelectedIndex = 0;
            }
            VIPBox.SelectedIndex = 0;
        }

        
        private void button4_Click(object sender, EventArgs e)
        {
            //获取分类
            comboBox1.Items.Clear();
            string url = "http://meik171.duapp.com/WallPaper?action=getSorts";
            string result = GetWebClient(url).Replace(" ", "").Replace("#*", "/");
            if (result != "" && result != "ER")
            {
                string[] list = result.Split('/');
                for (int i = 0; i < list.Length; i++)
                {
                    ListItem item = new ListItem();
                    string lld = list[i].Replace("#", "").Replace("*", "");
                    item.Text = lld.Split(',')[1];
                    item.Value = lld.Split(',')[0];
                    comboBox1.Items.Add(item);
                }
            }
        }
        public struct ListItem
        {
            public string Text;
            public string Value;
            public ListItem(string text, string value)
            {
                this.Text = text;
                this.Value = value;
            }
            public override string ToString()
            {
                return Text;
            }
        }


        private string GetWebClient(string url)
        {
            
            string strHTML = "";
            WebClient myWebClient = new WebClient();
            Stream myStream = myWebClient.OpenRead(url);
            StreamReader sr = new StreamReader(myStream, System.Text.Encoding.GetEncoding("utf-8"));
            strHTML = sr.ReadToEnd();
            myStream.Close();
            return strHTML;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //添加分类
            if (""!= sorttext.Text)
            {
                string encodeString = System.Web.HttpUtility.UrlEncode(sorttext.Text,System.Text.Encoding.UTF8);
            sorttext.Text = GetWebClient("http://meik171.duapp.com/WallPaper?action=AddSorts&sname=" + encodeString);

            comboBox1.Items.Clear();
            string url = "http://meik171.duapp.com/WallPaper?action=getSorts";
            string result = GetWebClient(url).Replace(" ", "").Replace("#*", "/");
            string[] list = result.Split('/');
            for (int i = 0; i < list.Length; i++)
            {
                ListItem item = new ListItem();
                string lld = list[i].Replace("#", "").Replace("*", "");
                item.Text = lld.Split(',')[1];
                item.Value = lld.Split(',')[0];
                comboBox1.Items.Add(item);
            }
           }
        }

       
       

        private void button2_Click(object sender, EventArgs e)
        {
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                packpath.Text = fbd.SelectedPath;
                path = fbd.SelectedPath;
                titleBox.Text = fbd.SelectedPath.Substring(fbd.SelectedPath.LastIndexOf(@"\") + 1);
                int index = this.dataGridView1.Rows.Add();
                this.dataGridView1.Rows[index].Cells[0].Value = titleBox.Text;
                this.dataGridView1.Rows[index].Cells[1].Value = fbd.SelectedPath;
                this.dataGridView1.Rows[index].Cells[2].Value = ((ListItem)comboBox1.SelectedItem).Value;
                this.dataGridView1.Rows[index].Cells[3].Value = VIPBox.SelectedIndex.ToString();

            }
  
        }
        private string[] getFiles(string Extention,string path) {
            string[] param = Extention.Split(',');
            List<string> list = new List<string>();
            DirectoryInfo dir = new DirectoryInfo(path);
            foreach (string p in param) {
                FileInfo[] files = dir.GetFiles(p);
                foreach (FileInfo f in files) {
                    list.Add(f.FullName);
                }
            }
            if (list.Count > 0)
            {
                string[] filew = new string[list.Count];
               list.CopyTo(filew,0);
               return filew;
            }
            else
            {
                return null;
            }
        } 
        private void button6_Click(object sender, EventArgs e)
        {
            if (packpath.Text != "" && titleBox.Text != "")
            {
                titleBox.ReadOnly = true;
                comboBox1.Enabled = false;
                VIPBox.Enabled = false;
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                button5.Enabled = false;
                Thread workerThread = new Thread(Upda);
                workerThread.Start();
            }
        }

       private void button5_Click(object sender, EventArgs e)
       {
           //删除分类
           if (null != comboBox1.SelectedItem) {
               string id = ((ListItem)comboBox1.SelectedItem).Value;
               sorttext.Text = GetWebClient("http://meik171.duapp.com/WallPaper?action=DelSorts&sid=" + id);
           }
           comboBox1.Items.Clear();
           string url = "http://meik171.duapp.com/WallPaper?action=getSorts";
           string result = GetWebClient(url).Replace(" ", "").Replace("#*", "/");
           if (result != ""&&result!="ER")
           {
               string[] list = result.Split('/');
               for (int i = 0; i < list.Length; i++)
               {
                   ListItem item = new ListItem();
                   string lld = list[i].Replace("#", "").Replace("*", "");
                   item.Text = lld.Split(',')[1];
                   item.Value = lld.Split(',')[0];
                   comboBox1.Items.Add(item);
               }
           }
       }

       public void MakeLiteImage(string imagePath) {
           String fname = imagePath.Substring(imagePath.LastIndexOf(@"\")+1);
           Bitmap sbmp = new Bitmap(imagePath);
           Image nbmp = new Bitmap(100, 100);
           System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(nbmp);
           g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
           g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
           g.DrawImage(sbmp, 0, 0, 100, 100);
           nbmp.Save("temp/l" + fname);
           nbmp.Dispose();
           sbmp.Dispose();
           
       }
       public string PadToLength(int length, char seed, string sstr,Encoding x) {
           string headstr = sstr;
           int headnum = x.GetBytes(headstr).Length;
           headstr = headstr.PadRight(headstr.Length + (length - headnum), seed);
           return headstr;
       }
       public byte[] getFilebytes(string path) {
           FileStream aFile = new FileStream(path, FileMode.Open);
           byte[] bb = new byte[aFile.Length];
           aFile.Read(bb, 0, (int)bb.Length);
           aFile.Dispose();
           aFile.Close();
           return bb;
       }
       public void Upda() {

 
           
               while(dataGridView1.RowCount>0)
               {
                   title=dataGridView1.Rows[0].Cells[0].Value.ToString();
                   sid = dataGridView1.Rows[0].Cells[2].Value.ToString();
                   path = dataGridView1.Rows[0].Cells[1].Value.ToString();
                   vips = dataGridView1.Rows[0].Cells[3].Value.ToString();
                   string litedes = "";
                   string bigdes = "";
                   string wid = Guid.NewGuid().ToString("N");
                   if (packpath.Text != "" && title != "")
                   {
                       string[] files = getFiles("*.jpg,*.png,*.JPEG", path);
                       DirectoryInfo dir = new DirectoryInfo("temp/");
                       if (dir.Exists)
                       {
                           foreach (FileInfo f in dir.GetFiles())
                           {
                               f.Delete();
                           }
                       }
                       else
                       {
                           dir.Create();
                       }
                       FileStream bs = new FileStream("temp/" + wid + ".bdt", FileMode.Create);
                       FileStream ls = new FileStream("temp/" + wid + ".ldt", FileMode.Create);
                       foreach (string f in files)
                       {

                           MakeLiteImage(f);
                       }
                       foreach (string f in files)
                       {
                           byte[] bb = getFilebytes(f);
                           bs.Write(bb, 0, bb.Length);
                           bigdes += bb.Length.ToString() + "&" + GetFileMd5(f) + ",";
                           FileInfo bf = new FileInfo(f);
                           byte[] lb = getFilebytes("temp/l" + bf.Name);
                           ls.Write(lb, 0, lb.Length);
                           litedes += lb.Length + "&" + GetFileMd5("temp/l" + bf.Name) + ",";
                       }
                       bs.Flush();
                       bs.Close();
                       ls.Flush();
                       ls.Close();
                       bigdes = bigdes.Substring(0, bigdes.Length - 1);
                       litedes = litedes.Substring(0, litedes.Length - 1) + "#";
                       FileStream ds = new FileStream("temp/" + wid + ".des", FileMode.Create);
                       byte[] lbyte = System.Text.Encoding.UTF8.GetBytes(litedes);
                       byte[] bbyte = System.Text.Encoding.UTF8.GetBytes(bigdes);
                       ds.Write(lbyte, 0, lbyte.Length);
                       ds.Write(bbyte, 0, bbyte.Length);
                       ds.Flush();
                       ds.Close();
                       if (RESTUpload("temp/" + wid + ".des"))
                       {
                           Toolabel.Text = wid + ".des上传成功！";
                       }
                       if (RESTUpload("temp/" + wid + ".ldt"))
                       {
                           Toolabel.Text = wid + ".ldt上传成功！";
                       }
                       if (RESTUpload("temp/" + wid + ".bdt"))
                       {
                           Toolabel.Text = wid + ".bdt上传成功！";
                       }
                       if (Addwp(wid, title, sid, vips))
                       {
                           Toolabel.Text = wid + "数据库添加成功！";
                       }

                   }
                   dataGridView1.Rows.RemoveAt(0);
                   if (dataGridView1.RowCount >1) {
                       Toolabel.Text = "开始休眠";
                       Thread.Sleep(int.Parse(TimeZone.Text));
                       Toolabel.Text = "休眠结束";
                   }

               }
               titleBox.ReadOnly = false;
               comboBox1.Enabled = true;
               button2.Enabled = true;
               button3.Enabled = true;
               button4.Enabled = true;
               button5.Enabled = true;
               VIPBox.Enabled = true;
             
       }

       public bool RESTUpload(string file)
       {
           string fname = file.Substring(file.LastIndexOf(@"/") + 1);
           string keys = GetWebClient("http://meik171.duapp.com/KeyMaker?action=getKey&Method=PUT&Bucket=meik-storage&Object=/"+fname);
           string url = "http://bcs.duapp.com/meik-storage/"+fname+"?sign=MBO:EBc9d7def393abe588e063fdd7db30ca:"+keys;
           HttpWebRequest uploadRequest = (HttpWebRequest)WebRequest.Create(url);//url为上传的地址
           uploadRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
           uploadRequest.Method = "PUT";
           uploadRequest.UserAgent = "baidu-bcs-java-sdk/1";
           uploadRequest.ProtocolVersion = HttpVersion.Version11;
           uploadRequest.Accept = "*/*";
           uploadRequest.KeepAlive = true;
           HttpWebResponse reponse;
           //创建一个内存流
           //确定上传的文件路径
           if (!String.IsNullOrEmpty(file))
           {

               //获取文件内容
               FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
               byte[] buffer = new byte[4096];
               int bytesRead = 0;
               int bbsd = 0;
               //将文件内容写进内存流
                uploadRequest.ContentLength = fileStream.Length;
               toolStripProgressBar1.Maximum=(int)fileStream.Length;
               Stream requestStream = uploadRequest.GetRequestStream();
               while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
               {
                   requestStream.Write(buffer, 0, bytesRead);
                   bbsd += bytesRead;
                   toolStripProgressBar1.Value = bbsd;
                   Toolabel.Text = fname + "已上传：" + bbsd * 100 / fileStream.Length + "%";
               }
               fileStream.Close();               
               requestStream.Close();
           }
           //获取到上传请求的响应
           reponse = (HttpWebResponse)uploadRequest.GetResponse();
           if (reponse.StatusCode == HttpStatusCode.OK)
           {
               return true;
           }
           else
           {
               return false;
           }
       }
      public bool Addwp(string wid,string title,string sid,string vip){
          bool result = true;
          string re = GetWebClient("http://meik171.duapp.com/WallPaper?action=Addwp&wid=" + wid + "&sid=" + sid+"&title="+title+"&vip="+vip);
          if (re == "OK")
          {
              result = true;
          }
          else {
              result = false;
          }
          return result;
      }
      public static string GetMD5(byte[] str)
      {
          StringBuilder sb = new StringBuilder();
          foreach (byte b in System.Security.Cryptography.MD5.Create().ComputeHash(str))
          {
              sb.Append(b.ToString("x2"));
          }
          return sb.ToString();
      }
      public static byte[] GetFileBytes(string filapath)
      {
          FileInfo f = new FileInfo(filapath);
          byte[] b1 = new byte[f.Length];
          FileStream aFile = new FileStream(filapath, FileMode.Open);
          aFile.Seek(0, SeekOrigin.Begin);
          aFile.Read(b1, 0, b1.Length);
          aFile.Dispose();
          aFile.Close();
          return b1;
      }
      public static string GetFileMd5(string path) {
          return GetMD5(GetFileBytes(path));
      }
      private void button7_Click(object sender, EventArgs e)
      {
          titleBox.ReadOnly = true;
          comboBox1.Enabled = false;
          VIPBox.Enabled = false;
          button2.Enabled = false;
          button3.Enabled = false;
          button4.Enabled = false;
          button5.Enabled = false;
          Thread workerThread = new Thread(Upda);
          workerThread.Start();

      }

      private void getsortbtn_Click(object sender, EventArgs e)
      {
          dataGridView3.Rows.Clear();
          string url = "http://meik171.duapp.com/WallPaper?action=getSorts";
          string result = GetWebClient(url).Replace(" ", "").Replace("#*", "/");
          if (result != "" && result != "ER")
          {
              string[] list = result.Split('/');
              for (int i = 0; i < list.Length; i++)
              {
                  string lld = list[i].Replace("#", "").Replace("*", "");
                  int index = this.dataGridView3.Rows.Add();
                  this.dataGridView3.Rows[index].Cells[0].Value = lld.Split(',')[0];
                  this.dataGridView3.Rows[index].Cells[1].Value = lld.Split(',')[1];
              }
          }
      }

      private void dataGridView3_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
      {
          string sid = e.Row.Cells[0].Value.ToString();
          MessageBox.Show(sid);
      }

      private void dataGridView3_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
      {
         ssinfo= dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
      }

      private void dataGridView3_CellEndEdit(object sender, DataGridViewCellEventArgs e)
      {
          string ninfo = dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
          if (ssinfo != ninfo) {
              string sid = dataGridView3.Rows[e.RowIndex].Cells[e.ColumnIndex-1].Value.ToString();
              MessageBox.Show( GetWebClient("http://meik171.duapp.com/WallPaper?action=UpdateSorts&sid=" + sid+"&sname="+ninfo));
          }
      }

      private void getWP_Click(object sender, EventArgs e)
      {
          dataGridView2.Rows.Clear();
          string url = "http://meik171.duapp.com/WallPaper?action=getNewAt&time=01";
          string result = GetWebClient(url);
          if (result.Length > 10) {
              result = result.Substring(1).Replace("#*", "*");
              string[] wpstr = result.Split('*');
              //0c8f1319776b4e52aaa16db6727baa22,浴室,15,20130713003739,1
              foreach (string a in wpstr)
              {
                  string[] wp = a.Split(',');
                  int index = this.dataGridView2.Rows.Add();
                  this.dataGridView2.Rows[index].Cells[0].Value = wp[0];
                  this.dataGridView2.Rows[index].Cells[1].Value = wp[1];
                  this.dataGridView2.Rows[index].Cells[2].Value = wp[4];
              }
          }
      }

      private void dataGridView2_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
      {
          R1 = dataGridView2.Rows[e.RowIndex];
      }

      private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
      {
          
              DataGridViewRow dr = dataGridView2.Rows[e.RowIndex];
              string dwid = dr.Cells[0].Value.ToString();
              string dtitle = dr.Cells[1].Value.ToString();
              string dvip = dr.Cells[2].Value.ToString();
              MessageBox.Show(GetWebClient("http://meik171.duapp.com/WallPaper?action=Updatewp&wid=" + dwid + "&title=" + dtitle+"&vip="+dvip));
      }

      private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
      {
          
      }

      private void getMsgBtn_Click(object sender, EventArgs e)
      {
          dataGridView4.Rows.Clear();
          string url = "http://meik171.duapp.com/Messager?action=getSug";
          string result = GetWebClient(url);
          if (result.Length > 10)
          {
              result = result.Substring(1).Replace("#*", "*");
              string[] wpstr = result.Split('*');
              //*3fd130d813fb4aee8a2415043dea8cd2,f942953c73cdc0788162b6c4685535a4,美女,20130716210932#
              foreach (string a in wpstr)
              {
                  string[] wp = a.Split(',');
                  int index = this.dataGridView4.Rows.Add();
                  this.dataGridView4.Rows[index].Cells[0].Value = wp[0];
                  this.dataGridView4.Rows[index].Cells[1].Value = wp[1];
                  this.dataGridView4.Rows[index].Cells[2].Value = wp[2];
                  this.dataGridView4.Rows[index].Cells[3].Value = wp[3];
              }
          }
      }


      private void dataGridView4_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
      {
          int i = e.RowIndex;
          if (i >= 0&&dataGridView4.Rows.Count>0) {
              string sid = dataGridView4.Rows[i].Cells[0].Value.ToString();
              string did = dataGridView4.Rows[i].Cells[1].Value.ToString();
              string sinfo = dataGridView4.Rows[i].Cells[2].Value.ToString();
              MessageEditor me = new MessageEditor(sid, did, sinfo);
              me.ShowDialog();
              dataGridView4.Rows.Clear();
              string url = "http://meik171.duapp.com/Messager?action=getSug";
              string result = GetWebClient(url);
              if (result.Length > 10)
              {
                  result = result.Substring(1).Replace("#*", "*");
                  string[] wpstr = result.Split('*');
                  //*3fd130d813fb4aee8a2415043dea8cd2,f942953c73cdc0788162b6c4685535a4,美女,20130716210932#
                  foreach (string a in wpstr)
                  {
                      string[] wp = a.Split(',');
                      int index = this.dataGridView4.Rows.Add();
                      this.dataGridView4.Rows[index].Cells[0].Value = wp[0];
                      this.dataGridView4.Rows[index].Cells[1].Value = wp[1];
                      this.dataGridView4.Rows[index].Cells[2].Value = wp[2];
                      this.dataGridView4.Rows[index].Cells[3].Value = wp[3];
                  }
              }
          }
      }

      private void button1_Click(object sender, EventArgs e)
      {
          string sid = "";
          string did = "public";
          string sinfo = "";
          MessageEditor me = new MessageEditor(sid, did, sinfo);
          me.ShowDialog();
      }

      

    }

}
